const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    activityList: [], // 活动列表数据
    currentTab: '0', // 当前选中的标签页，0表示我发起的，1表示我参加的
    page: 1, // 当前页码
    pageSize: 10, // 每页数据量
    hasMoreData: true, // 是否还有更多数据
    loading: false, // 是否正在加载数据
    qrCodeVisible: false, // 二维码弹窗是否可见
    currentActivity: null // 当前选中的活动
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 初始化页面数据
    this.loadActivityList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // 页面显示时的处理逻辑
    this.loadActivityList();
  },

  /**
   * 加载活动列表数据
   */
  loadActivityList: function() {
    var that = this;
    // 显示加载状态
    that.setData({
      loading: true
    });
    
    // 获取接口地址，根据当前标签页选择不同的接口
    let apiName = '';
    if (that.data.currentTab === '0') {
      // 我发起的活动列表接口
      apiName = 'plugin.commerce.api.commerce-activity.my-initiated-activities';
    } else if (that.data.currentTab === '1') {
      // 我参加的活动列表接口
      apiName = 'plugin.commerce.api.commerce-activity.my-participated-activities';
    }
    
    // 实际API调用
    app._getNetWork({
      url: app.getNetAddresss(apiName),
      data: {
        page: that.data.page,
        pageSize: that.data.pageSize
      },
      success: function(res) {
        var response = res.data;
        if (response.result === 1) {
          var data = response.data;
          if (that.data.page === 1) {
            that.setData({
              activityList: data.list || [],
              hasMoreData: data.list && data.list.length >= that.data.pageSize
            });
          } else {
            that.setData({
              activityList: that.data.activityList.concat(data.list || []),
              hasMoreData: data.list && data.list.length >= that.data.pageSize
            });
          }
        } else {
          wx.showToast({
            title: response.msg || '获取活动列表失败',
            icon: 'none'
          });
        }
      },
      fail: function(res) {
        wx.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      },
      complete: function() {
        that.setData({
          loading: false
        });
      },
      state: true
    });
    
    // 为了在没有真实接口的情况下仍能看到效果，保留模拟数据
    // 实际项目中可以注释掉这部分
    setTimeout(function() {
      // 模拟数据 - 添加了qrCode字段用于展示二维码
      const mockData = [
        {
          id: '1',
          title: '与非化石能源·商务互荐会',
          cover: '/image/activity/1.jpg',
          startTime: '2025-03-20',
          endTime: '2025-03-20',
          activity_status: '1', // 0: 报名中, 1: 活动中, 2: 已结束, 3: 未开始
          joinCount: 13,
          isCreator: true // 我发起的
        },
        {
          id: '2',
          title: '家德佛山会员新年起航大会',
          cover: '/image/activity/2.jpg',
          startTime: '2025-02-20',
          endTime: '2025-02-20',
          activity_status: '2',
          joinCount: 50,
          isCreator: true // 我发起的
        },
        {
          id: '3',
          title: '家德佛山分会企业访谈',
          cover: '/image/activity/3.jpg',
          startTime: '2025-01-17',
          endTime: '2025-01-17',
          activity_status: '2',
          joinCount: 20,
          isCreator: false, // 我参加的
          qrCode: '/image/qrcode.png' // 二维码图片地址
        },
        {
          id: '4',
          title: '新能源技术分享会',
          cover: '/image/activity/4.jpg',
          startTime: '2025-04-15',
          endTime: '2025-04-15',
          activity_status: '0',
          joinCount: 35,
          isCreator: false, // 我参加的
          qrCode: '/image/qrcode.png' // 二维码图片地址
        }
      ];
      
      // 根据当前标签页过滤数据
      let filteredData = [];
      if (that.data.currentTab === '0') {
        // 我发起的
        filteredData = mockData.filter(item => item.isCreator === true);
      } else if (that.data.currentTab === '1') {
        // 我参加的
        filteredData = mockData.filter(item => item.isCreator === false);
      }
      
      // 只有在API调用失败时才使用模拟数据
      if (that.data.loading) {
        that.setData({
          activityList: filteredData,
          loading: false,
          hasMoreData: false // 模拟没有更多数据
        });
      }
    }, 1500);
  },

  /**
   * 切换标签页
   */
  onTabChange: function(e) {
    const tabIndex = e.currentTarget.dataset.index;
    this.setData({
      currentTab: tabIndex,
      page: 1,
      activityList: []
    });
    this.loadActivityList();
  },

  /**
   * 查看活动详情
   */
  onActivityDetail: function(e) {
    const activityId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageX/activity_detail/activity_detail?id=' + activityId
    });
  },

  /**
   * 创建新活动
   */
  onCreateActivity: function() {
    wx.navigateTo({
      url: '/packageX/activity_create/activity_create'
    });
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    this.setData({
      page: 1,
      activityList: []
    });
    this.loadActivityList();
    wx.stopPullDownRefresh();
  },

  /**
   * 上拉加载更多
   */
  onReachBottom: function() {
    if (this.data.hasMoreData && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      });
      this.loadActivityList();
    }
  },

  /**
   * 显示二维码弹窗 - 先调用接口获取二维码
   */
  onShowQrCode: function(e) {
    const activity = e.currentTarget.dataset.activity;
    const that = this;
    
    // 显示加载提示
    wx.showLoading({
      title: '获取二维码中',
    });
    
    // 调用获取二维码接口
    app._getNetWork({
      url: app.getNetAddresss('plugin.commerce.api.commerce-activity.qr-code-url'),
      data: {
        activity_id: activity.id
      },
      success: function(res) {
        var response = res.data;
        if (response.result === 1) {
          // 将获取到的二维码URL设置到活动对象中
          const updatedActivity = {
            ...activity,
            qrCode: response.data.miQrCodeUrl || ''
          };
          
          that.setData({
            currentActivity: updatedActivity,
            qrCodeVisible: true
          });
        } else {
          wx.showToast({
            title: response.msg || '获取二维码失败',
            icon: 'none'
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      },
      complete: function() {
        wx.hideLoading();
      },
      state: true
    });
  },

  /**
   * 关闭二维码弹窗
   */
  onCloseQrCode: function() {
    this.setData({
      qrCodeVisible: false,
      currentActivity: null
    });
  }
});